package org.qq.clientthread;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.tree.DefaultMutableTreeNode;
import org.qq.ui.GroupRoom;
import org.qq.ui.PrivateChatRoom;
import org.qq.util.ClientAllData;

/**
 * 
 * project_name:QQ
 * package_name:org.link.clientthread
 * file_name:LoginThread.java
 * @author Link
 * create_date:2015年8月29日 下午2:03:09
 * modified_date:
 * description: 用户登录线程
 *
 */
public class ClientLoginThread extends Thread{
	private Socket s;							//套接字
	private String reply;						//接收来自服务器的答复
	private JFrame jframe;						//窗体
	private BufferedReader br = null;			//输入流
	private PrintStream ps = null;				//输出流
	private GroupRoom groupRoom;				//群聊
	private String loginName;					//登录用户名
	private PrivateChatRoom privateChatRoom;	//私聊
	
	public ClientLoginThread() {
		super();
	}
	
	public ClientLoginThread(Socket s) {
		super();
		this.s = s;
	}

	public ClientLoginThread(Socket s,JFrame jframe,String loginName) {
		super();
		this.s = s;
		this.jframe = jframe;
		this.loginName = loginName;
		try {
			br = new BufferedReader(new InputStreamReader(s.getInputStream()));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void run() {
		while(true){
			try {
				reply = br.readLine();
				//System.out.println(reply);
			} catch (IOException e) {
				return;
			}
			if(reply.endsWith("true----login")){//如果答复为true,表示输入的账号密码正确
				jframe.dispose();//关闭之前窗口
				groupRoom = new GroupRoom(s,loginName);
				groupRoom.setVisible(true);//同时打开聊天窗口
				groupRoom.setTitle(loginName);
			}else if(reply.equals("online----login")){//账号是否已登录
				JOptionPane.showMessageDialog(null, "该账号已登录,请勿重复登录!");
			}else if(reply.endsWith("false----login")){//密码和账号不匹配
				JOptionPane.showMessageDialog(null, "输入的用户名或密码错误,请重新输入!");
			}else if(reply.endsWith("groupChat")){//群聊
				acceptGroupMessage(reply);
			}else if(reply.endsWith("----onlineUser")){//在线好友list
				DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(reply.substring(0, reply.length()-14));
				DefaultMutableTreeNode parentNode = groupRoom.getOnline();
				groupRoom.getTreeModel().insertNodeInto(newNode, parentNode, parentNode.getChildCount());
			}else if(reply.endsWith("----offlineUser")){//离线好友list
				DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(reply.substring(0, reply.length()-15));
				DefaultMutableTreeNode parentNode = groupRoom.getOffline();
				groupRoom.getTreeModel().insertNodeInto(newNode, parentNode, parentNode.getChildCount());
			}else if(reply.startsWith("----login----")){//好友上线
				moveChildOfflineNode(reply.substring(13, reply.length()));//调用好友上线刷新好友列表方法
			}else if(reply.startsWith("----offline----")){//好友下线
				moveChildOnlineNode(reply.substring(15, reply.length()));//好友离线后刷新好友列表方法
			}else if(reply.endsWith("----privateChat")){//私人聊天
				acceptPrivateMessage(reply);//调用私聊方法
			}
		}
	}
	/**
	 * 
	 * description: 向服务器发消息
	 * 2015年8月31日 上午10:31:57
	 * @author Link
	 * void
	 *
	 */
	public synchronized void sendMessageToServer(String str1){
		try {
			ps = new PrintStream(s.getOutputStream());
			ps.println(str1);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 
	 * description: 接收群聊用户消息
	 * 2015年9月1日 下午4:34:22
	 * @author Link
	 * void
	 *
	 */
	public synchronized void acceptGroupMessage(String reply1){
		String message = reply1.substring(0, reply1.length()-13);		//截取群信息部分
		String[] message1 = message.split("::::");
		//groupRoom.getTextArea().setCaretPosition(groupRoom.getTextArea().getText().length());//设置垂直滚动条一直在最小方
		groupRoom.getTextArea().append(new SimpleDateFormat("HH:mm:ss").format(new Date())+"  "+message1[0]+"  say:"+"\n"+message1[1]+"\n");
		groupRoom.getTextArea().setCaretPosition(groupRoom.getTextArea().getText().length());
	}
	/**
	 * 
	 * description: 接收私聊消息
	 * creatTime:2015年9月5日上午11:38:02
	 * @author Link
	 * return type: void
	 *
	 */
	public synchronized void acceptPrivateMessage(String reply){
		String messageAndSendUser = reply.substring(0, reply.length()-15);//截取有用信息部分
		String[] str = messageAndSendUser.split("--%%");
		privateChatRoom = new PrivateChatRoom(s);
		String nickName = str[1].substring(0, str[1].length()-10);
		privateChatRoom.setTitle(str[1]);
		if(judgeprivateChatRoom(privateChatRoom)){//判断此好友窗口是否已经被New出来
			acceptMessage(str[1], str[0], nickName);//调用接收消息方法
		}else{
			newPrivateChatRoom(privateChatRoom, str[0],nickName);//调用new出私聊窗口方法
		}
	}
	
	/**
	 * 
	 * description: 判断privateChat是否被new出来了
	 * creatTime:2015年9月5日下午3:51:47
	 * @author Link
	 * return type: boolean
	 *
	 */
	public boolean judgeprivateChatRoom(PrivateChatRoom pcr){
		for(int i = 0;i<ClientAllData.privateChatRooms.size();i++){
			if(pcr.equals(ClientAllData.privateChatRooms.get(i))){
				return true;
			}
		}
		return false;
	}
	
	/**
	 *  
	 * description: new出私聊窗口
	 * 2015年9月6日 上午9:19:06
	 * @author Link
	 * void
	 *
	 */
	public void newPrivateChatRoom(PrivateChatRoom privateChatRoom,String message,String nickName){
		privateChatRoom.setVisible(true);
		privateChatRoom.getTextArea().append(new SimpleDateFormat("HH:mm:ss").format(new Date())+"  "+nickName+"  say:"+"\n"+message+"\n");
		privateChatRoom.getTextArea().setCaretPosition(privateChatRoom.getTextArea().getText().length());//设置光标位置
		ClientAllData.privateChatRooms.add(privateChatRoom);
	}
	
	/**
	 * 
	 * description: 接收私聊信息
	 * creatTime:2015年9月5日下午3:40:51
	 * @author Link
	 * return type: void
	 *
	 */
	public void acceptMessage(String title,String message,String nickName){
		for(int i = 0;i<ClientAllData.privateChatRooms.size();i++){
			if(ClientAllData.privateChatRooms.get(i).getTitle().toString().equals(title)){
				ClientAllData.privateChatRooms.get(i).getTextArea().append(new SimpleDateFormat("HH:mm:ss").format(new Date())+"  "+nickName+"  say:"+"\n"+message+"\n");
				ClientAllData.privateChatRooms.get(i).getTextArea().setCaretPosition(ClientAllData.privateChatRooms.get(i).getTextArea().getText().length());
			}
		}
	}
	
	/**
	 * 
	 * description: 好友上线后刷新好友列表
	 * creatTime:2015年9月5日下午6:07:06
	 * @author Link
	 * return type: void
	 *
	 */
	public void moveChildOfflineNode(String name){
		DefaultMutableTreeNode offlineParentNode = groupRoom.getOffline();//离线好友父节点
		@SuppressWarnings({ "unchecked" })
		Enumeration<DefaultMutableTreeNode> childrenNode = offlineParentNode.children();
		while(childrenNode.hasMoreElements()){
			DefaultMutableTreeNode child = childrenNode.nextElement();
			String path = child.toString();
			if(path.equals(name)){
				child.removeFromParent();//移除
				groupRoom.getjTree().updateUI();//jtree重新画图
			}
		}
		DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(name);
		DefaultMutableTreeNode onlineParentNode = groupRoom.getOnline();
		groupRoom.getTreeModel().insertNodeInto(newNode, onlineParentNode, 0);
	}
	/**
	 * 
	 * description: 好友离线后刷新好友列表
	 * creatTime:2015年9月5日下午6:46:21
	 * @author Link
	 * return type: void
	 *
	 */
	public void moveChildOnlineNode(String name){
		DefaultMutableTreeNode onlineParentNode = groupRoom.getOnline();//离线好友父节点
		@SuppressWarnings({ "unchecked" })
		Enumeration<DefaultMutableTreeNode> childrenNode = onlineParentNode.children();//获取父节点中所有子节点
		while(childrenNode.hasMoreElements()){
			DefaultMutableTreeNode child = childrenNode.nextElement();
			String path = child.toString();
			if(path.equals(name)){
				child.removeFromParent();//移除
				groupRoom.getjTree().updateUI();//jtree重新画图
			}
		}
		DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(name);
		DefaultMutableTreeNode offlineParentNode = groupRoom.getOffline();
		groupRoom.getTreeModel().insertNodeInto(newNode,offlineParentNode, 0);
	}
}







